﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Xml;
using NopSolutions.NopCommerce.BusinessLogic.Model;

namespace NopSolutions.NopCommerce.BusinessLogic.Providers
{
    public class BnrExchangeRateProvider : IExchangeRateProvider
    {
        #region IExchangeRateProvider Members

        public List<ExchangeRate> GetCurrencyLiveRates(string exchangeRateCurrencyCode) {
            var exchangeRates = new List<ExchangeRate>();

            var request = WebRequest.Create("http://www.bnr.ro/nbrfxrates.xml") as HttpWebRequest;
            using (WebResponse response = request.GetResponse()) {
                XmlDocument document = new XmlDocument();
                document.Load(response.GetResponseStream());

                //XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable);
                //nsmgr.AddNamespace("ns", "http://www.bnr.ro/xsd");
                //nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");

                XmlNode node = document.SelectSingleNode("DataSet/Body/Cube");
                var updateDate = DateTime.ParseExact(node.Attributes["date"].Value, "yyyy-MM-dd", null);

                NumberFormatInfo provider = new NumberFormatInfo();
                provider.NumberDecimalSeparator = ".";
                provider.NumberGroupSeparator = "";
                foreach (XmlNode node2 in node.ChildNodes) {
                    exchangeRates.Add(new ExchangeRate() {
                        CurrencyCode = node2.Attributes["currency"].Value,
                        Rate = decimal.Parse(node2.Value, provider),
                        UpdatedOn = updateDate
                    }
                    );
                }
            }

            return exchangeRates;
        }

        public string Name {
            get { return "National Bank of Romania"; }
        }

        #endregion
    }
}
